/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package networkowner;

import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
import contractmessageservice.ContractMessage;
import contractmessageservice.PartyType;
import electricitysupplier.ResponseMessage;
import electricitysupplier.T1ES1;
import java.io.StringReader;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.transform.stream.StreamSource;

/**
 *
 * @author ool
 */
@MessageDriven(mappedName = "jms/esit1no1_Queue", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class Esit1no1mdb implements MessageListener {
    
   private static final String T1NO1 = "T1NO1";
    private final T1ES1 service;
    private DerbyDao dao;
    private MessageValidatorService messageValidatorService;

    public Esit1no1mdb() {
        messageValidatorService = new MessageValidatorService();
        //dao = new DerbyDao();
        service = new T1ES1();
    }

    @Override
    public void onMessage(Message message) {
        try {
            TextMessage msg = (TextMessage) message;
            JAXBContext context = JAXBContext.newInstance(ContractMessage.class);
            Unmarshaller um = context.createUnmarshaller();
            ContractMessage contractMessage = (ContractMessage) um.unmarshal(new StreamSource(new StringReader((msg.getText()))));

            //int id = dao.insertRecievedMessage(msg.getText());
            
            ResponseMessage resp = new ResponseMessage();
            resp.setMessageRecieverParty(contractMessage.getMessageSenderParty());
            resp.setMessageSenderParty(T1NO1);
            //resp.setMessageId(Integer.toString(id));

            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(new Date());
            XMLGregorianCalendar xmlCal = new XMLGregorianCalendarImpl(cal);
            resp.setTime(xmlCal);
            
            resp.setProcessedMessageId(contractMessage.getMessageId());
            validateContractMessage(contractMessage, resp);

            sendAperak(resp);
            Logger.getLogger(Esit1no1mdb.class.getName()).info("SUCCESS ");
        } catch (JMSException ex) {
            Logger.getLogger(Esit1no1mdb.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(Esit1no1mdb.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void sendAperak(ResponseMessage msg) throws JAXBException {
//        ReceiveAperak aperak = new ReceiveAperak();
//        aperak.setMsg(msg);
//        JAXBContext context = JAXBContext.newInstance(ReceiveAperak.class);
//        Marshaller marshaller = context.createMarshaller();
//        StringWriter writer = new StringWriter();
//        marshaller.marshal(aperak, writer);
        //int id = dao.insertComposedMessage(writer.toString());
        //msg.setMessageId(Integer.toString(id));
        
        
        electricitysupplier.IT1ES1Service port = service.getBasicHttpBindingIT1ES1Service();
        port.receiveAperak(msg);
    }

    private void validateContractMessage(ContractMessage contractMessage, ResponseMessage resp) {
        boolean result = true;
        StringBuilder message = new StringBuilder();
        ContractMessage.ClientParty clientParty = contractMessage.getClientParty();
        PartyType providerParty = contractMessage.getProviderParty();
        ContractMessage.ContractInfo contractInfo = contractMessage.getContractInfo();
        if (messageValidatorService.isClientInDb(clientParty.getRegistryCode())) {
            result = false;
            message.append("Client not in db. ");
        }
        if (messageValidatorService.isProviderInDb(providerParty.getRegistryCode())) {
            result = false;
            message.append("Crovider not in db. ");
        }
        if (!messageValidatorService.clientHasContract(clientParty.getRegistryCode(), contractInfo.getStartDate().toGregorianCalendar().getTime())) {
            result = false;
            message.append("Client already has a contract. ");
        }
        resp.setAccepted(result);
        if (!result) {
            resp.setMessage(message.toString());
        }

    }
}